package com.koron.plan.web.repairplan.notified;

import com.koron.common.core.business.workflow.bean.po.SysWorkflow;
import com.koron.common.core.business.workflow.bean.properties.WorkflowProperties;
import com.koron.common.core.business.workflow.service.SysWorkflowService;
import com.koron.common.core.business.workflow.templates.WorkFlowHandler;
import com.koron.plan.config.Constants;
import com.koron.plan.web.repairplan.bean.vo.PlanPackageVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author twcao
 * @title: RepairPlanSubmit
 * @projectName GDH_EAM_V2
 * @description: 提交时的处理操作
 * @date 2021/9/1410:46
 */
@Slf4j
@Component
public class RepairPlanSubmit implements RepairPlanNotify<PlanPackageVO> {

    private ThreadLocal<Map<String, PlanPackageVO>> packageHolder = new ThreadLocal<>();

    @Autowired
    private SysWorkflowService workflowService;

    @Autowired
    private WorkFlowHandler workFlowHandler;

    @Override
    public boolean initializeBefore(SessionFactory factory, final PlanPackageVO vo) {
        Map<String, PlanPackageVO> map = new HashMap<>(4);
        map.put(Constants.REPAIR_PACKAGE_EVENT_KEY.INITIALIZE_BEFORE, vo.clone());
        packageHolder.set(map);
        return true;
    }

    @Override
    public boolean saveBefore(SessionFactory factory, final PlanPackageVO vo) {
        Map<String, PlanPackageVO> map = packageHolder.get();
        map.put(Constants.REPAIR_PACKAGE_EVENT_KEY.SAVE_BEFORE, vo.clone());
        packageHolder.set(map);
        return true;
    }

    @Override
    public boolean saveAfter(SessionFactory factory, final PlanPackageVO vo) {
        // 1、创建工作流
        List<SysWorkflow> sysWorkflows = workflowService.queryByDataId(vo.getId());
        if(!CollectionUtils.isEmpty(sysWorkflows)) {
            return true;
        }
        // 指定下个节点审批人id
        Map<String, String> formVariables = new HashMap<>(2);
        WorkflowProperties prop = WorkflowProperties.init(Constants.REPAIR_PACKAGE_WORKFLOW.PROCESS_CODE);
        SysWorkflow workflow = workFlowHandler.start(prop, vo.getId(), vo.getCode(), vo.getName(), formVariables);
        log.info("工作流创建成功， billId = {}", workflow.getBillId());
        packageHolder.remove();
        return true;
    }

    @Override
    public boolean filter(SessionFactory factory, final PlanPackageVO vo) {
        // 提交后是待审核状态
        return Constants.REPAIR_PACKAGE_STATE.TO_AUDIT.equals(vo.getStatus());
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
